<template>
	<el-dialog width="99%" :close-on-click-modal="false" v-model="dialogVisible" :title="state.title" destroy-on-close :before-close="handleClose">
		<div class="header-search">
			<!-- 公司主体和团队 -->
			<FunctionalSelect
				v-model="state.queryForm.companyIds"
				:optionFormat="{
					key: 'id',
					label: 'name',
				}"
				useRadio
				:options="state.companyList"
				placeholder="公司主体"
				@query-list="handleSearch($event, 'companyIds')"
				class="right-ml10 w180"
			/>
			<FunctionalSelect
				v-model="state.queryForm.teamIds"
				:optionFormat="{
					key: 'id',
					label: 'name',
				}"
				useRadio
				:options="state.teamList"
				placeholder="团队"
				@query-list="handleSearch($event, 'teamIds')"
				class="right-ml10 w180"
			/>
			<!-- 仓库 -->
			<pop-cascader
				@query-list="handleSearch($event, 'whIds')"
				:options="state.whList"
				v-model="state.queryForm.whIds"
				:placeholder="'仓库'"
				:confirmDatatype="'1'"
				class="right-ml10 w180"
			/>
			<!-- 操作人 -->
			<pop-cascader
				@query-list="handleSearch($event, 'createBys')"
				:options="state.useList"
				v-model="state.queryForm.createBys"
				:placeholder="'操作人'"
				:confirmDatatype="'1'"
				class="right-ml10 w180"
			/>
			<!-- 操作时间 -->
			<date-picker-with-prefix :options="state.datePickerOptions" @change="changeDataRange" ref="datePickerRef" />
		</div>
		<!-- :fetch-list="wmsInventoryBatchRecord" -->
		<table-layout
			ref="dataTableRef"
			row-key="id"
			:tree-props="{ children: 'recordItems' }"
			:fetch-list="wmsInventoryBatchRecord"
			:query-form="state.queryForm"
			:span-method="arraySpanMethod"
			height="50vh"
			:header-cell-style="{ color: '#000', background: '#F5F7FA' }"
			:row-class-name="tableRowClassName"
			:default-expand-all="true"
			border
		>
			<template v-slot:tableLayout>
				<el-table-column min-width="50"></el-table-column>
				<el-table-column label="公司主体" prop="companyName" min-width="200">
					<template v-slot="scope">
						<div class="main-row" v-if="scope.row.recordItems">
							<el-descriptions :column="5" style="width: 100%">
								<el-descriptions-item width="26%">
									<el-link type="primary" @click="toDownLoad(scope.row, '1')">{{ scope.row.fileName }}</el-link>
								</el-descriptions-item>
								<el-descriptions-item label="操作时间：" width="22%">
									{{ scope.row.createTimestamp }}
								</el-descriptions-item>
								<el-descriptions-item label="操作人：" width="18%">
									{{ scope.row.createBy }}
								</el-descriptions-item>
								<el-descriptions-item label="执行状态：" width="18%">
									{{ scope.row.status === '0' ? '解析中' : scope.row.status === '1' ? '解析失败' : scope.row.status === '2' ? '解析成功' : '' }}
								</el-descriptions-item>
								<template v-if="scope.row.status === '1'">
									<el-descriptions-item>
										<el-link type="danger" @click="toDownLoad(scope.row, '2')">下载错误文件</el-link>
									</el-descriptions-item>
									<el-descriptions-item span="5" label="错误原因：">
										{{ JSON.parse(scope.row.importErrorReason).errMsg }}
									</el-descriptions-item>
								</template>
							</el-descriptions>
						</div>
					</template>
				</el-table-column>
				<el-table-column label="团队" prop="teamName" min-width="100"></el-table-column>
				<el-table-column label="备货区域" prop="stockupAreaName" min-width="120"></el-table-column>
				<el-table-column label="备货平台" prop="stockupPlatformName" min-width="120"></el-table-column>
				<el-table-column label="所属仓库" prop="whCode" min-width="120"></el-table-column>
				<el-table-column label="SKU" prop="skuCode" min-width="100"></el-table-column>
				<el-table-column label="MSKU/FNSKU" prop="" min-width="120">
					<template v-slot="scope">
						<div>{{ scope.row.msku || '--' }}</div>
						<div>{{ scope.row.fnsku || '--' }}</div>
					</template>
				</el-table-column>
				<el-table-column label="存放仓库" prop="positionCode" min-width="120"></el-table-column>
				<el-table-column label="初始数据" prop="initQty" min-width="120"></el-table-column>
			</template>
		</table-layout>
	</el-dialog>
</template>
<script setup lang="ts" name="seatTransferDialog">
import { getCompanyTeamTree, getwhTree, getUsersTree } from '/@/api/transferSlip/index';
import { wmsInventoryBatchRecord } from '/@/api/inventory/index';
import { downBlobFile } from '/@/utils/other';
const state = reactive({
	title: '初始化库存记录',
	infoData: [{ id: '1', recordItems: [{ id: '2' }] }],
	queryForm: {
		companyIds: [],
		teamIds: [],
		whId: [],
		createBys: [],
		startCreateTimestamp: '',
		endCreateTimestamp: '',
	},
	whList: [],
	companyList: [],
	teamList: [],
	useList: [],
	datePickerOptions: [{ label: '采购日期', value: 1 }],
});
const dialogVisible = ref(false);
const dataTableRef = ref();
const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
	if (row.recordItems) {
		// row.recordItems
		if (columnIndex === 1) {
			return [1, 9];
		} else if (columnIndex > 1 && columnIndex < 10) {
			return [0, 0];
		} else {
			return [1, 1];
		}
	}
};
// 打开弹窗
const openDialog = async () => {
	getUsersTreeOpt();
	getCompanyTeamOpt();
	getwhTreeOpt();
	dialogVisible.value = true;
};
// 关闭弹窗
const handleClose = () => {
	dialogVisible.value = false;
	state.infoData = [];
};
// 操作人
const getUsersTreeOpt = async () => {
	const { data } = await getUsersTree();
	state.useList = formatUsersTree(data);
};
const formatUsersTree = (data) => {
	return data.map((item) => {
		item.key = item.id;
		item.label = item.name;
		if (item.subList) {
			item.children = formatUsersTree(item.subList);
		}
		return item;
	});
};
// 获取公司主体
const getCompanyTeamOpt = async () => {
	const { data } = await getCompanyTeamTree();
	state.companyList = data;
	data.map((item) => {
		if (item.subList) {
			state.teamList = [...state.teamList, ...item.subList];
		}
	});
};
// 仓库
const getwhTreeOpt = async () => {
	const { data } = await getwhTree({});
	state.whList = formatWhTree(data);
};
// 初始化仓库树形结构
const formatWhTree = (data) => {
	return data.map((item) => {
		item.key = item.nodeCode;
		item.label = item.nodeName;
		if (item.children) {
			item.children = formatWhTree(item.children);
		}
		return item;
	});
};
const handleSearch = (ids: string[], type) => {
	state.queryForm[type] = ids;
	// 公司团队联动
	if (type === 'companyIds') {
		state.teamList = [];
		state.queryForm.teamIds = [];
		state.companyList.forEach((item) => {
			if (ids.indexOf(item.id) !== -1 && item.subList) {
				state.teamList = [...state.teamList, ...item.subList];
			}
		});
	}
	toRefresh();
};

const changeDataRange = (val: unknown, v2: string[]) => {
	if (val === 1) {
		state.queryForm.startCreateTimestamp = v2[0] ? v2[0] + ' 00:00:00' : '';
		state.queryForm.endCreateTimestamp = v2[1] ? v2[1] + ' 23:59:59' : '';
	}
	toRefresh();
};
const tableRowClassName = ({ row, rowIndex }) => {
	if (row.recordItems) {
		return 'row-header';
	}
	return '';
};
const toDownLoad = async (row, status) => {
	if (status === '1') {
		if (row.fileUrl) {
			await downBlobFile(row.fileUrl, {}, row.fileName);
		}
	} else if (status === '2') {
		if (row.importErrorUrl) {
			await downBlobFile(row.importErrorUrl, {}, row.importErrorUrl.split('/').at(-1));
		}
	}
};
const toRefresh = () => {
	dataTableRef?.value.refresh();
};
defineExpose({
	openDialog,
});
</script>
<style scoped>
:deep(.date-picker-prefix) {
	display: inline-flex;
}
.right-ml10 {
	margin-right: 10px !important;
}
.header-search {
	padding: 0 16px 0 16px;
}
.header-search > div {
	margin-bottom: 10px;
}
.main-row {
	display: inline-flex;
	gap: 50px;
	width: 100%;
}
.main-row .el-link {
	justify-content: flex-start;
}
:deep(.el-table .row-header td) {
	background-color: #f5f7fa !important;
}
:deep(.el-descriptions__cell) {
	vertical-align: top;
}
:deep(.el-descriptions__label) {
	color: #909399;
	text-align: right;
}
</style>
